<?php
/**
* Letterman Newsletter Component
* 
* @package Letterman
* @author Soeren
* @copyright Soeren Eberhardt <soeren@virtuemart.net>
*   (who just needed an easy and *working* Newsletter component for Mambo 4.5.1 and mixed up Newsletter and YaNC)
* @copyright Mark Lindeman <mark@pictura-dp.nl> 
*    (parts of the Newsletter component by Mark Lindeman; Pictura Database Publishing bv, Heiloo the Netherland)
* @copyright Adam van Dongen <adam@tim-online.nl>
*    (parts of the YaNC component by Adam van Dongen, www.tim-online.nl)
*    
* @copyright Philip Sylvain <contact@sphilip.com>
*  	(MVC refactorization and AJAX)
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*
*/

// no direct access
defined('_JEXEC') or die();

jimport('joomla.application.component.model');

class LettermanModelNewsletters extends JModel
{
	
	var $row = null;
	
	function getId()
	{
		$cid = $this->getCid();
		
		if (empty($cid[0])) {
			//try to see id
			return JRequest::getInt('id', 0);
		}
		
		return $cid[0] ;
	}
	
	function getCid()
	{
		$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
		JArrayHelper::toInteger( $cid, array(0) );
		
		return $cid ;
	}
	
	
	function &getRow()
	{
		if ( !is_object($this->row) ) {
			
			$this->row =& $this->getTable('letterman');
			$this->row->load( $this->getId() );
		} 

		return $this->row;
	}
	
	
	function checkout()
	{
		$user = & JFactory::getUser();
		$row = & $this->getRow();
		
		/*
		 * If the item is checked out we cannot edit it... unless it was checked
		 * out by the current user.
		 */
		if ( $row->isCheckedOut( $user->get('id'), $row->checked_out )) {
			$msg = JText::sprintf('DESCBEINGEDITTED', JText::_('The newsletter'), $row->subject);
			JError::raiseWarning( 200, $msg );
			return false;
		}
		
		$row->checkout($user->get('id'));
		
		return true ;
		
	}
	
	
	function getItems()
	{
		$result = array();
		$mainframe = &JFactory::getApplication();
	
		$context = 'com_letterman.newsletters' ;
		$default_limit = $mainframe->getCfg('list_limit');
		
		$limit = $mainframe->getUserStateFromRequest( $context.'limit', 'limit', $default_limit, 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $context.'limitstart', 'limitstart', 0, 'int' );
		$search = $mainframe->getUserStateFromRequest( $context.'search', 'search', '', 'string' );
		$search = $this->_db->getEscaped( trim( strtolower( $search ) ) );
	
		$where = '';
		if ($search) {
			$where = ' WHERE a.subject LIKE \'%' . $search . '%\' OR a.message LIKE \'%' .$search . '%\'';
		}
	
		$sql = 'SELECT a.*, u.name AS editor, g.name AS groupname'
			 . PHP_EOL . 'FROM #__letterman AS a'
			 . PHP_EOL . 'LEFT JOIN #__users AS u ON u.id = a.checked_out'
			 . PHP_EOL . 'LEFT JOIN #__groups AS g ON g.id = a.access'
			 . PHP_EOL . $where .' ORDER BY created DESC';

		$rows = $this->_getList( $sql , $limitstart, $limit );
	
		if ( !$this->_db->getErrorNum() ) {
	            
	        $result['limitstart'] = $limitstart ;
			$result['limit'] = $limit ; 
			$result['total'] = $this->_getListCount( $sql );
	        $result['rows'] = $rows ;
	        $result['search'] = $search ;       
	
	    } else {
	            JError::raiseWarning( 200, $this->_db->getErrorMsg() );
	            return false;
	    }
	         
	    return $result ;
	}
	
	
	
	function save()
	{
		$row = & $this->getRow();
		
		$mailDatas = array(
			'subject' => JRequest::getString('subject', ''),
			'html_message' => JRequest::getVar( 'html_message', '', 'POST', 'string', JREQUEST_ALLOWRAW )
		);
		
		$newsletterDatas = JRequest::getVar( 'newsletter', array() , 'POST' , 'array' );
		
		$datas = array_merge( $mailDatas, $newsletterDatas );
		
		if ( !$row->bind($datas) ) {
            JError::raiseWarning( 200, $row->getError() );
            return false;
        }
        
        $row->check();
       
        if ( !$row->store() ) {
            JError::raiseWarning( 200, $row->getError() );
            return false;
        }
        
        //check newsletter
        $row->checkin();
        
        return true;
		
	}
	
	function publish( $bool )
	{
		$cid = $this->getCid();
		$user	= & JFactory::getUser();
		$uid	= $user->get('id');
		
		$cids = implode( ',', $cid );

		$query = 'UPDATE #__letterman SET published='. (int) $bool . PHP_EOL 
		       . 'WHERE id IN ( '. $cids .' ) AND ( checked_out = 0 OR (checked_out = '. (int) $uid .' ) )';
				
		$this->_db->setQuery($query);
		
		if (!$this->_db->query()) {
			JError::raiseError( 500, $this->_db->getErrorMsg() );
			return false;
		}

		if (count($cid) == 1) {
			$row =& $this->getTable('letterman');
			$row->checkin($cid[0]);
		}
		
		return true;
	}
	
	function remove()
	{
		$cids = implode( ',', $this->getCid() );
		
		$this->_db->setQuery( 'DELETE FROM #__letterman WHERE id IN (' . $cids . ')' );
		
		if ( !$this->_db->query() ) {
			JError::raiseError( 500, $this->_db->getErrorMsg() );
			return false;
		}
		
		return true;
	}
	
	function &send( $post )
	{
		$params =& Com_Letterman::getParams();
		
		//debut config
		$smtp_method = $params->get('smtp_method', 0);
		$smtp_auth =  $params->get('smtp_auth', '');
		$smtp_host = $params->get('smtp_host', '');
		$smtp_user = $params->get('smtp_user', '');
		$smtp_password = $params->get('smtp_password', '');
		$sendmail_method = $params->get('sendmail_method', 0);
		$sendmail_path = $params->get('sendmail_path', '');
		$php_method = $params->get('php_method', 1);
		$charset = $params->get('charset', 'utf-8');
		$disable_timeout = $params->get('disable_timeout', 1);
		$mails_per_step = $params->get('mails_per_step', 50);
		//fin config

		$mainframe =& JFactory::getApplication();
		
		if($disable_timeout) {
			@set_time_limit(0);
		}
		
		$limitstart = isset($post->limitstart) ? intval($post->limitstart) : 0 ;
		
		$response = new stdClass();
		$response->error = '';
		$response->nextlimitstart = 0;
		$response->percent = 100;
		$response->total = 0;
		
		jimport('joomla.mail.helper');
		jimport('joomla.mail.mail');
		
		$mailfrom = JMailHelper::cleanAddress( $post->mailfrom );
		$replyto = JMailHelper::cleanAddress( $post->replyto );
		$only_confirmed = intval( $post->only_confirmed );
		$textformat = intval( $post->textformat);
		
		//email validation
		if ( !JMailHelper::isEmailAddress($mailfrom) ) {
			$response->error = JText::sprintf( 'Invalid email', $mailfrom );
			return $response;
		}
		
		if ( !JMailHelper::isEmailAddress($replyto) ) {
			$response->error = JText::sprintf( 'Invalid email', $replyto );
            return $response;
		}
		
		//get the thewsletter
		$newsletter =& $this->getRow();
		
		//add message footer
		$siteName = $mainframe->getCfg('sitename');
		$live_site = str_replace('administrator/', '', JURI::base());
		
		$unsubscribeLink = $live_site . 'index.php?option=com_letterman&do=unsubscribe' ;
		$unsubscribeLink = '<a href="'. $unsubscribeLink .'" >' .$unsubscribeLink .'</a>' ;
		
		$footer = JText::sprintf('NEWSLETTER_FOOTER', $siteName, $unsubscribeLink );
		
		$newsletter->html_message .= $footer ;
		
		if($textformat) {
			$replace = array('<br>', '<br />', '<br/>', '</p>', '</h1>', '</h2>','</h3>','</h4>', '<div>', '</div>' );
			$newsletter->html_message = str_replace( $replace, PHP_EOL , $newsletter->html_message) ;
			$newsletter->html_message = html_entity_decode(strip_tags($newsletter->html_message)) ;
		}
		
		//get subscribers list
		$where = $only_confirmed ? ' WHERE confirmed=1' : '' ;
		$sql = 'SELECT `name`, `email` FROM `#__letterman_subscribers`' . $where ;
		$rows = $this->_getList( $sql, $limitstart, $mails_per_step );
		
		$mail = new JMail();
		
		if( $smtp_method ){
			if($smtp_auth){
				$mail->useSMTP(true, $smtp_host, $smtp_username, $smtp_password) ;
			} else {
				$mail->useSMTP(false, $smtp_host) ;
			}
		} elseif ($sendmail_method) {
			$mail->useSendmail($sendmail_path) ;
		}
		
		$mail->setSender(array($mailfrom, $siteName));
		$mail->addReplyTo($replyto);
		$mail->IsHTML(!$textformat);
		
		$errors= 0;
		
		foreach($rows as $subscriber){
			
			$mail->addRecipient($subscriber->email);
			$name = empty($subscriber->name) ? JText::_('Subscriber') : $subscriber->name;
			$mail->setBody(str_replace( "[NAME]", $name, $newsletter->html_message));
			$mail->setSubject(str_replace( "[NAME]", $name, $newsletter->subject));
			if (!$mail->Send()){
				$errors++;
			}
			
			$mail->ClearAddresses();
		}
		
		if($errors){
			$response->error = JText::printf('Mails don\'t sent', $errors);
		}
		
		$fetched = $limitstart + count($rows) ;
		$total = $this->_getListCount( $sql );
		$response->percent = round( (100 * $fetched) / $total );
		$response->nextlimitstart = $fetched < $total ? $fetched : $total ;
		$response->total = $total ;
		
		return $response;
	}
	
}
